import employees from '../models/employee'
import Conflicted from '../errors/conflicted'
import NotFound from '../errors/NotFoundError'
import BadRequest from '../errors/badReques'
import { CREATED_CODE } from '../errors/statusCode'

export const createEmployee = (req, res, next) => {
  const {
    firstName,
    lastName,
    middleName,
    birthDay,
    comment,
    config,
    isActive,
    email,
    phone,
    telegram,
    sex,
    grade,
    photo
  } = req.body;
  employees.create({
    firstName,
    lastName,
    middleName,
    birthDay: new Date(birthDay),
    comment,
    config,
    isActive,
    email,
    phone,
    telegram,
    sex,
    grade,
    photo
  })
    .then((employee) => res.send(employee))
    .catch((evt) => {
      if (evt.name === 'ValidationError') {
        next(
          new BadRequest(
            'Переданы некорректные данные при создании карточки сотрудника',
          ),
        );
      } else {
        next(evt)
      }
    })
}
export  const getEmployees = (req, res, next) => {
    employees.find({isActive: true})
      .then((employees) => {
        res.send(employees);
      })
      .catch(next)
}

export const updateEmployee = (req, res, next) => {
  const {
    firstName,
    lastName,
    middleName,
    birthDay,
    comment,
    config,
    isActive,
    email,
    phone,
    telegram,
    sex,
    grade,
    photo
  } = req.body;
  employees.findByIdAndUpdate(
    req.params.employeeId,
    {
      firstName,
      lastName,
      middleName,
      birthDay: new Date(birthDay),
      comment,
      config,
      isActive,
      email,
      phone,
      telegram,
      sex,
      grade,
      photo
    },
    {
      new: true,
      runValidators: true,
    },
  )
    .orFail(() => {
      throw new NotFound('Сотрудник с указанным _id не найден')
    })
    .then((employee) => {
      res.send(employee)
    })
    .catch((evt) => {
      if (evt.code === 11000) {
        next(new Conflicted('Такое задание уже существует'))
      } else if (evt.name === 'ValidationError') {
        next(new BadRequest('Переданы некорректные данные при обновлении задания'))
      } else {
        next(evt)
      }
    })
}

export const deleteEmployee = (req, res, next) => {
  const { } = req.body;
  employees.findByIdAndUpdate(
    req.params.employeeId,
    {
      isActive: false,
    },
    {
      new: true,
      runValidators: true,
    },
  )
    .orFail(() => {
      throw new NotFound('Сотрудник с указанным _id не найден')
    })
    .then((employee) => {
      res.send(employee)
    })
    .catch((evt) => {
      if (evt.code === 11000) {
        next(new Conflicted('Такое задание уже существует'))
      } else if (evt.name === 'ValidationError') {
        next(new BadRequest('Переданы некорректные данные при обновлении задания'))
      } else {
        next(evt)
      }
    })
}
